import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class FootballLeague {
    private static final String FILE_PATH = "league_table.txt";
    private List<Team> teams;

    public static void main(String[] args) {
        FootballLeague league = null;
        try {
            league = new FootballLeague(FILE_PATH);
        } catch (IOException e) {
            System.err.println("Error reading the league table file: " + e.getMessage());
            return;
        }

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter home team: ");
        String homeTeam = scanner.nextLine();
        if (!isValidTeam(league, homeTeam)) {
            System.err.println("Invalid home team name.");
            return;
        }
        System.out.print("Enter away team: ");
        String awayTeam = scanner.nextLine();
        if (!isValidTeam(league, awayTeam)) {
            System.err.println("Invalid away team name.");
            return;
        }
        System.out.print("Enter home team score: ");
        int homeScore = readScore(scanner);
        System.out.print("Enter away team score: ");
        int awayScore = readScore(scanner);

        league.processMatchResult(homeTeam, awayTeam, homeScore, awayScore);
        league.printLeagueTable();
        try {
            league.updateLeagueTableFile(FILE_PATH);
        } catch (IOException e) {
            System.err.println("Error writing to the league table file: " + e.getMessage());
        }
    }

    public FootballLeague(String filename) throws IOException {
        teams = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = br.readLine())!= null) {
                String[] data = line.split(",");
                Team team = new Team(data[0]);
                team.setMatchesPlayed(Integer.parseInt(data[1]));
                team.setWins(Integer.parseInt(data[2]));
                team.setDraws(Integer.parseInt(data[3]));
                team.setLosses(Integer.parseInt(data[4]));
                team.setGoalsFor(Integer.parseInt(data[5]));
                team.setGoalsAgainst(Integer.parseInt(data[6]));
                team.setPoints(Integer.parseInt(data[7]));
                teams.add(team);
            }
        }
    }

    public void processMatchResult(String homeTeamName, String awayTeamName, int homeGoals, int awayGoals) {
        Team homeTeam = findTeam(homeTeamName);
        Team awayTeam = findTeam(awayTeamName);

        homeTeam.updateResults(homeGoals, awayGoals);
        awayTeam.updateResults(awayGoals, homeGoals);
    }

    private Team findTeam(String name) {
        for (Team team : teams) {
            if (team.getName().equals(name)) {
                return team;
            }
        }
        return null;
    }

    public void printLeagueTable() {
        Collections.sort(teams);
        for (Team team : teams) {
            System.out.println(team);
        }
    }

    private static boolean isValidTeam(FootballLeague league, String teamName) {
        return league.findTeam(teamName)!= null;
    }

    private static int readScore(Scanner scanner) {
        while (!scanner.hasNextInt()) {
            System.out.println("Invalid score. Please enter a valid integer.");
            scanner.next();
        }
        return scanner.nextInt();
    }

    public void updateLeagueTableFile(String filename) throws IOException {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
            for (Team team : teams) {
                bw.write(team.getName() + "," + team.getMatchesPlayed() + "," + team.getWins() + "," +
                        team.getDraws() + "," + team.getLosses() + "," + team.getGoalsFor() + "," +
                        team.getGoalsAgainst() + "," + team.getPoints());
                bw.newLine();
            }
        }
    }

    private static class Team implements Comparable<Team> {
        private String name;
        private int matchesPlayed;
        private int wins;
        private int draws;
        private int losses;
        private int goalsFor;
        private int goalsAgainst;
        private int points;

        public Team(String name) {
            this.name = name;
            this.matchesPlayed = 0;
            this.wins = 0;
            this.draws = 0;
            this.losses = 0;
            this.goalsFor = 0;
            this.goalsAgainst = 0;
            this.points = 0;
        }

        public String getName() {
            return name;
        }

        public int getMatchesPlayed() {
            return matchesPlayed;
        }

        public int getWins() {
            return wins;
        }

        public int getDraws() {
            return draws;
        }

        public int getLosses() {
            return losses;
        }

        public int getGoalsFor() {
            return goalsFor;
        }

        public int getGoalsAgainst() {
            return goalsAgainst;
        }

        public int getPoints() {
            return points;
        }

        public void setMatchesPlayed(int matchesPlayed) {
            this.matchesPlayed = matchesPlayed;
        }

        public void setWins(int wins) {
            this.wins = wins;
        }

        public void setDraws(int draws) {
            this.draws = draws;
        }

        public void setLosses(int losses) {
            this.losses = losses;
        }

        public void setGoalsFor(int goalsFor) {
            this.goalsFor = goalsFor;
        }

        public void setGoalsAgainst(int goalsAgainst) {
            this.goalsAgainst = goalsAgainst;
        }

        public void setPoints(int points) {
            this.points = points;
        }

        public void updateResults(int goalsFor, int goalsAgainst) {
            this.matchesPlayed++;
            this.goalsFor += goalsFor;
            this.goalsAgainst += goalsAgainst;
            if (goalsFor > goalsAgainst) {
                this.wins++;
                this.points += 3;
            } else if (goalsFor == goalsAgainst) {
                this.draws++;
                this.points++;
            } else {
                this.losses++;
            }
        }

        @Override
        public String toString() {
            return String.format("%-15s %2d %2d %2d %2d %2d %2d %2d",
                    name, matchesPlayed, wins, draws, losses, goalsFor, goalsAgainst, points);
        }

        @Override
        public int compareTo(Team other) {
            if (this.points!= other.points) {
                return Integer.compare(other.points, this.points);
            }
            int goalDifferenceThis = this.goalsFor - this.goalsAgainst;
            int goalDifferenceOther = other.goalsFor - other.goalsAgainst;
            if (goalDifferenceThis!= goalDifferenceOther) {
                return Integer.compare(goalDifferenceOther, goalDifferenceThis);
            }
            return Integer.compare(other.goalsFor, this.goalsFor);
        }
    }
}
